package com.cloudxingkong.dianyinke.NewTeacher.Ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.PhotoUtils;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

public class UploadingVideo extends AppCompatActivity implements View.OnClickListener {

    private FrameLayout shangchuan;
    private EditText miaoshu;
    private Spinner spinner;


    private ArrayAdapter<String> stringArrayAdapter;
    private String note;

    private static final int SELECT_PIC_BY_TAKE_VIDEO = 1;
    private static final int SELECT_PIC_BY_PICK_VIDEO = 2;

    private static final int RESULT_VIDEO=311;

    private Uri videoUri;
    private String videoPath;
    private MediaMetadataRetriever retriever;
    private ImageView ivCover;
    private EditText etTitle;
    private String title;
    private String spSelectItem;
    private SharedPreferences sharedPreferences;
    private String sessionID;
    private File videoFile;
    private ProgressDialog progressDialog;
    private Spinner tgSpinner;
    private String tgSpinnerItem;
    private String coverPic;
    /** 更新数据*/
    private int UPDATE_VIDEO=-1;
    private String videoID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uploading_video);
        init();

        /** Spinner*/
        stringArrayAdapter = new ArrayAdapter<String>(this,
                android.support.v7.appcompat.R.layout.support_simple_spinner_dropdown_item,
                Constans.VIDEO_TGTGRP);
        spinner.setAdapter(stringArrayAdapter);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.support.v7.appcompat.R.layout.support_simple_spinner_dropdown_item,
                Constans.VIDEO_LABEL);
        tgSpinner.setAdapter(adapter);

        shangchuan.setOnClickListener(this);
    }

    private void init() {
        shangchuan = (FrameLayout) findViewById(R.id.uvling_shangchuan);
        miaoshu = (EditText) findViewById(R.id.uvling_et_note);
        spinner = (Spinner) findViewById(R.id.uv_spinner);
        tgSpinner = (Spinner) findViewById(R.id.uv_tgtgrp_spinner);
        etTitle = (EditText) findViewById(R.id.uvling_et_title);
        ivCover = (ImageView) findViewById(R.id.uvling_iv_cover);
        retriever = new MediaMetadataRetriever();
        sharedPreferences = getSharedPreferences("data_dyk", 0);
        sessionID = CookieHelper.getSessionID(sharedPreferences);

        String updataLesson = getIntent().getStringExtra("updateVideo");
        if (updataLesson!=null&&updataLesson.equals("102")){
            updateLesson();
            UPDATE_VIDEO=0;
        }
    }

    private void updateLesson() {
        String vTitle = sharedPreferences.getString("vTitle", "");
        String vNote = sharedPreferences.getString("vNote", "");
        videoID = sharedPreferences.getString("vID", "");
        etTitle.setText(vTitle);
        miaoshu.setText(vNote);
    }

    public void save(View view) {
        switch (view.getId()){
            case R.id.uving_back:
                finish();
                break;
            case R.id.uving_save:
                uploadVideo();
                break;
        }
    }

    private void uploadVideo() {
        if (TextUtils.isEmpty(miaoshu.getText())||
                TextUtils.isEmpty(etTitle.getText())){
            Toast.makeText(UploadingVideo.this, "请添加视频描述", Toast.LENGTH_SHORT).show();
            return;
        }else{
            note = miaoshu.getText().toString();
            title = etTitle.getText().toString();
        }
        progressDialog = ProgressDialog.show(this, null, "正在上传请稍后...", true, false);
        spSelectItem = spinner.getSelectedItem().toString();
        tgSpinnerItem = tgSpinner.getSelectedItem().toString();
        Log.e("test", "视频分类 ：" + tgSpinnerItem);

        if (UPDATE_VIDEO == 0) {
            RequestParams params1 = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.VIDEO_SAVE);
            params1.addHeader("cookie",sessionID);
            params1.addBodyParameter("id", videoID);
            params1.addBodyParameter("title", title);
            params1.addBodyParameter("note", note);
            params1.addBodyParameter("type", tgSpinnerItem);
            params1.addBodyParameter("tgtgrp", spSelectItem);
            x.http().post(params1, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Message msg1=handler.obtainMessage();
                    msg1.what=2;
                    msg1.obj=result;
                    handler.sendMessage(msg1);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    progressDialog.dismiss();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }else{
            RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.UPLOAD_VIDEO);
            params.addHeader("cookie", sessionID);
            params.setMultipart(true);
            params.addBodyParameter("title", title);
            params.addBodyParameter("note", note);
            params.addBodyParameter("type", tgSpinnerItem);
            params.addBodyParameter("tgtgrp", spSelectItem);
            params.addBodyParameter("filedata",videoFile);
            params.addBodyParameter("coverpic",new File(coverPic));

            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.e("test","上传视频结果 : "+result);
                    Message msg=handler.obtainMessage();
                    msg.what=1;
                    msg.obj=result;
                    handler.sendMessage(msg);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    progressDialog.dismiss();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }


    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    String result= (String) msg.obj;
                    if (result.contains("true")) {
                        Toast.makeText(UploadingVideo.this, "上传成功", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_VIDEO);
                        progressDialog.dismiss();
                        finish();
                    }else{
                        Toast.makeText(UploadingVideo.this, "上传失败,请稍后重试!", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                    break;
                case 2:
                    String update= (String) msg.obj;
                    Log.e("test","修改视频中的描述信息 "+update);
                    if (update.contains("true")) {
                        Toast.makeText(UploadingVideo.this, "更新成功", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_VIDEO);
                        progressDialog.dismiss();
                        finish();
                    }else{
                        Toast.makeText(UploadingVideo.this, "更新失败,请稍后重试!", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                    break;
            }
        }
    };

    //选择视频
    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("提示").setMessage("您想如何上传该视频？")
                .setNegativeButton("我要拍摄", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        takePhoto();
                    }
                })
                .setNeutralButton("忽略", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
        .create().show();
    }

    private void pickPhoto() {
        Intent intent = new Intent();
        intent.setType("video/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_PIC_BY_PICK_VIDEO);
    }

    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, SELECT_PIC_BY_TAKE_VIDEO);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {   //resultCode=-1   requestCode=1 data = null
        if (resultCode== Activity.RESULT_OK){
            doVideo(requestCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void doVideo(int requestCode, Intent data) {

        if(requestCode == SELECT_PIC_BY_TAKE_VIDEO )
        {
            if(data == null)
            {
                Toast.makeText(this, "选择视频文件出错", Toast.LENGTH_LONG).show();
                return;
            }
            videoUri = data.getData();
            if(videoUri == null )
            {
                Toast.makeText(this, "选择视频文件出错", Toast.LENGTH_LONG).show();
                return;
            }
        }
        String[] pojo = {MediaStore.Images.Media.DATA};
        Cursor cursor =  getContentResolver().query(videoUri,pojo,null,null,null);
        if(cursor != null )
        {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            videoPath = cursor.getString(columnIndex);
            cursor.close();
        }
        Log.i("test", "videoPath = " + videoPath);
        videoFile = new File(videoPath);
        if (videoFile.exists()) {
            retriever.setDataSource(videoFile.getAbsolutePath());
            Bitmap bitmap = retriever.getFrameAtTime();
            if (bitmap != null) {
                ivCover.setVisibility(View.VISIBLE);
                shangchuan.setVisibility(View.GONE);
                ivCover.setImageBitmap(bitmap);


                coverPic = PhotoUtils.saveImg(bitmap);
                Log.e("test","bitmap转为file "+"\n文件路径 "+coverPic);

            }else{
                Toast.makeText(UploadingVideo.this, "获取缩略图失败", Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(UploadingVideo.this, "文件不存在", Toast.LENGTH_SHORT).show();
        }
    }




}
